package org.wpahs.ahn.rssfeed;

import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.util.Log;
import android.webkit.URLUtil;

import org.apache.http.HttpEntity;
import org.w3c.dom.Document;
import org.wpahs.ahn.rssfeed.DB.DBFeedItem;
import org.wpahs.ahn.rssfeed.DB.DBMyFeed;

import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.net.ssl.HttpsURLConnection;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

/** Wow Great
 * Created by dgambone on 02/17/2015.
 */
public class FeedGetter extends AsyncTask<Void,Void,List<Feed>> {

    private List<MyFeed> mMyFeeds = null;
    private Context context = null;
    private HttpEntity entity = null;

    public FeedGetter(List<MyFeed> feeds,Context context){
        mMyFeeds = feeds;
        this.context = context;

    }
    @Override
    protected List<Feed> doInBackground(Void... params) {
        List<Feed> results = new ArrayList<>();
        Document doc;

        for(MyFeed feed : mMyFeeds) {
            Log.i("RSSGetService", "Handling Intent - " + feed.getId() + " - " + feed.getUrl());
            try {
                HttpURLConnection connection;
                URL urlConnection = new URL(feed.getUrl());
                if(!URLUtil.isHttpsUrl(feed.getUrl())){
                    connection = (HttpURLConnection) urlConnection
                            .openConnection();
                }else{
                    connection = (HttpsURLConnection) urlConnection
                            .openConnection();
                }
                connection.setDoInput(true);
                connection.connect();
                InputStream input = connection.getInputStream();
                DocumentBuilderFactory dbf =
                        DocumentBuilderFactory.newInstance();
                DocumentBuilder db = dbf.newDocumentBuilder();
                doc = db.parse(input);
                Feed result = new Feed(feed.getId(),doc);

                results.add(result);
                connection.disconnect();
            } catch (org.apache.http.conn.HttpHostConnectException e) {
                Log.e("FeedGetter", e.getMessage());
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return results;
    }

    @Override
    protected void onPostExecute(List<Feed> result) {
        super.onPostExecute(result);
        for(Feed feed : result) {
            try {
                saveFeed(feed);
            } catch (Exception ex) {
                Log.e("FeedDownloader",ex.getMessage());
            }
        }
        if(mMyFeeds.size() == 1) { //probably all
            broadcastFeedDone(mMyFeeds.get(0).getId(), mMyFeeds.get(0).getTitle());
        }else if (mMyFeeds.size() > 1){
            broadcastFeedDone(0, "All");
        }else{
            broadcastFeedDone(0,"weird"); //just in case
        }

        try{
            if(entity != null){
                entity.consumeContent();
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }

    }

    private void saveFeed(Feed feed){
        //update the feed's info.
        DBMyFeed fs = new DBMyFeed(context);
        MyFeed myFeed = fs.getFeed(feed.getFeedId());
        fs.close();
        if(feed != null){
            myFeed.setLastUpdated(new Date());
            myFeed.setTitle((feed.getTitle() == null ? feed.getLink() : feed.getTitle() ));
            myFeed.setSubtitle(feed.getDescription());
            fs.updateFeed(myFeed);
            Log.i("RSSGetService", "Updated feed " + myFeed.getId());
            //todo: only download every so often
            new SiteInfoDownloader(myFeed,feed.getLink(),feed.getFeedImage(),context).execute(); // get the favicon everytime so far
            DBFeedItem dbItem = null;

            try {
                for (FeedItem feedItem : feed.getItems()) {
                    dbItem = new DBFeedItem(context);
                    int id = dbItem.existsByURL(feedItem.getLink());
                    dbItem.close();
                    if (id > 0) { //already exists.
                        feedItem.setItemId(id);
                        dbItem = new DBFeedItem(context);
                        String dbImage = dbItem.getImage(id);
                        dbItem.close();
                        if (dbImage != null && dbImage.length() > 0) {
                            // prolly set.  Skip downloading image
                            Log.i("RSSGetService-saveFeed", "Already exists.  No Updates: " + feedItem.getItemId() + " - " + feedItem.getTitle());
                        } else {
                            //dbItem.setImage(id,downloadImage(feedItem.imageToDownload()));
                            //new ImageDownloader(feedItem).execute();
                            Log.i("RSSGetService-saveFeed", "Already exists.  Skipping Image Download: " + feedItem.getItemId() + " - " + feedItem.getTitle());

                        }
                    } else { // it's a new item.  Download and set image
                        //just save it as is.  We'll find out if it has an image using ImageDownloader
                        try {
                            dbItem = new DBFeedItem(context);
                            feedItem.setHasImage(false);
                            feedItem.setItemId(dbItem.addToDB(feedItem));
                            dbItem.close();
                            Log.i("ImageFinder", "new feed : " + String.valueOf(feedItem.getItemId()) +
                                    feedItem.getTitle());
                            String imageToDownload = feedItem.imageToDownload();
                            if(imageToDownload != null){
                                Image img = new Image();
                                img.setId(feedItem.getFeedId());
                                img.setSubId(feedItem.getItemId());
                                img.setDownloadType(Downloader.DownloadType.FeedItemImage);
                                img.setUrl(imageToDownload);
                                Downloader.addImageToQueue(context,img);
                            }else { // try to find an image elsewhere.
                                new ImageFinder(feedItem, context).execute();
                            }

                        } catch (Exception e) {
                            Log.e("Saving New Feed", e.getMessage());
                        }
                        Log.i("RSSGetService-saveFeed", "New Item: " + myFeed.getId());
                    }
                }
            }catch (Exception ex){
                Log.e("RSSGetService-Saving",ex.getMessage());
            }
            if(dbItem != null && dbItem.isOpen()){
                dbItem.close();
            }

        }else{
            Log.i("RSSGetService", "Feed was null " + myFeed.getId() + " - " + myFeed.getUrl());
        }
    }

    private void broadcastFeedDone(int feedId, String title){
        Intent intent = new Intent(RSSGetService.FEED_DONE);
        intent.putExtra(context.getResources().getString(R.string.feed_id), feedId);
        intent.putExtra(context.getResources().getString(R.string.feedTitle), title);
        context.sendBroadcast(intent);
    }




}

